//
//  ST_ReceiveFollowViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/26.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SDWebImage
import MJRefresh
import HandyJSON

class ST_ReceiveFollowViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("收到关注")
        
        view.backgroundColor = Color.white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.bottom.right.left.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        self.request_data()
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data() {
        
        currentPage += 1
        
        JVrequest(PH.fetchFansListApi,parameters: ["page":currentPage] ,success: { (json) in
            
            let data = json["data"]
            
//            self.total = data["total"].intValue
            
            var count = 0
            
            if let list = [ST_BTUserinfo].deserialize(from: data["list"].rawString() ?? "") as? [ST_BTUserinfo]{
        
                if self.currentPage == 1{
                    self.data_array = list
                }else{
                    self.data_array += list
                }
                
                count = list.count
            }
            
            self.collectionView.mj_header?.endRefreshing()
            
            self.collectionView.reloadData {
                
                
                self.load_more_option_style(tableView: self.collectionView, count: count, pageSize: 20) {
                    
                    self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                        self?.request_data()
                    })
                }
                
            }
            
            
            
        }) { (code, err) in
            
            self.collectionView.mj_header?.endRefreshing()
            self.toast(text: err)
        }
        
        
    }
        
//    MARK: - Properties
    lazy var itemWidth:CGFloat = {
        return ScreenWidth
    }()
    
    lazy var itemHeight = 106.cgFloat
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.init(width: itemWidth, height: itemHeight)
        
//        layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 65)
        
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
//        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        collection.register(cellWithClass: ST_ReceiveFollowCell.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
    
    fileprivate var data_array = [ST_BTUserinfo]()

}

extension ST_ReceiveFollowViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ReceiveFollowCell.self, for: indexPath)
        
        let cellModel = self.data_array[indexPath.item]
        
        cell.model = cellModel
        
        return cell
    }
    
    
}


//MARK: - Cell
fileprivate class ST_ReceiveFollowCell:UICollectionViewCell{
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        contentView.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize.init(width: 50, height: 50))
            make.top.left.equalToSuperview().offset(15)
        }
        
        contentView.addSubview(nickname_label)
        nickname_label.snp.makeConstraints { (make) in
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.top.equalTo(avatar_image_view).offset(1)
            make.height.equalTo(25)
            if ScreenWidth < 380{
                make.width.lessThanOrEqualTo(100)
            }
        }
        
        contentView.addSubview(time_label)
        time_label.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.top.equalTo(nickname_label.snp.bottom).offset(3)
            make.height.equalTo(17)
        }
        
        contentView.addSubview(sign_image_container)
        sign_image_container.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label.snp.right).offset(4)
            make.centerY.equalTo(nickname_label).offset(-1)
            make.height.equalTo(18)
            make.width.equalTo(70)
        }
        
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.bottom.equalToSuperview().offset(-15)
            make.height.equalTo(20)
        }
        
        
        contentView.addSubview(follow_btn)
        follow_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatar_image_view)
            make.right.equalToSuperview().offset(-15)
            make.width.equalTo(68)
            make.height.equalTo(36)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//    MARK: Properties

    fileprivate lazy var avatar_image_view:UIImageView = {
         let control = UIImageView()
          control.contentMode = .scaleAspectFill
          control.cornerRadius = 25
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
          return control
      }()
   

    fileprivate lazy var nickname_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()

    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#ACB4C0")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var sign_image_container:ST_UserSignView = {
        let control = ST_UserSignView()
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = "关注了你"
        control.textColor = Color.init(hexString: "#61666F")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var follow_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 36/2.0
        control.setTitle("关注", for: UIControl.State.normal)
        control.setTitle("已关注", for: UIControl.State.selected)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0x42CEDA)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.selected)
        control.setTitleColorForAllStates(UIColor.white)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        
        control.addTarget(self, action: #selector(follow_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
  
    @objc fileprivate func follow_handle(){
        
        let info = ST_MatchUserInfo.init(accid: model.accid, avatar: model.avatar, nickname: model.nickname)
        
        FollowBehavior(info: info, followControl: follow_btn) { (matched, err) in
            
            if let e = err{
                self.parentViewController?.toast(text: e)
            }else{
                
                self.model.is_attention = self.follow_btn.isSelected
            }
        }
   }
    
    var model = ST_BTUserinfo(){
        didSet{
            
            avatar_image_view.pin_setImage(from: model.avatar.compress_small_image(width: 400).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            nickname_label.text = model.nickname
            
            follow_btn.isSelected = model.is_attention
            time_label.text = model.create_int.double.b_t_global_date_string()
            
            
            sign_image_container.bind_data(isVip: CHECK_MEMBER_STATUS(expirationTime: model.vip_expire) == .subscribe, detectedFace: model.face_audit_state == 3)
            
            
            
        }
    }
    
    @objc fileprivate func push_user_center_handle(){
        
        
            let vc = ST_PairsCenterViewController()
            
            vc.accid = self.model.accid

            let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
            
            nav.overCurrentContext = true
            
            GlobalPresent(toController: nav)
            
  
        
    }
}
